package com.interviewbackend.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.IService;
import com.interviewbackend.dto.InterviewConfigDTO;
import com.interviewbackend.dto.InterviewStateDTO;
import com.interviewbackend.entity.InterviewSession;
import com.interviewbackend.service.EvaluationService;
import com.interviewbackend.service.InterviewFlowService;
import com.interviewbackend.service.InterviewSessionService;
import com.interviewbackend.util.SpeechSynthesisUtil;
import com.interviewbackend.util.TagUtil;
import com.interviewbackend.vo.ResultVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.scheduling.annotation.Async;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/interview")
public class InterviewFlowController {

    @Autowired
    private InterviewFlowService interviewFlowService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private EvaluationService evaluationService; // ✅ 注入评估服务
    @Autowired private StringRedisTemplate stringRedisTemplate;
    @Autowired private SpeechSynthesisUtil speechSynthesizerUtil;
    @Autowired private InterviewSessionService interviewSessionService;
    public static final String NEXT_QUESTION_RESULT_PREFIX = "interview:next_question_result:";

    @PostMapping("/resume")
    public ResultVO<Map<String, Object>> uploadResumeFile(@RequestParam("userId") Long userId,
                                                   @RequestParam("file") MultipartFile file) throws IOException {
        // 1. 处理简历并返回 interviewId、keywords、jobType
        Map<String, Object> resumeResult = interviewFlowService.processResume(userId, file);

        // 2. 拿到 interviewId → 根据关键词和岗位生成子题库
        Long interviewId = (Long) resumeResult.get("interviewId");
        interviewFlowService.generateSubQuestionSet(interviewId);

        return ResultVO.success(resumeResult);
    }

    // 输入配置
    @PostMapping("/configure")
    public ResultVO<String> configureInterview(@RequestBody InterviewConfigDTO dto) throws IOException {
        interviewFlowService.configureInterview(dto);
        return ResultVO.success("面试配置成功"); // 不返回题目，返回确认消息
    }

    @PostMapping("/next-question")
    public ResultVO<Map<String, Object>> requestNextQuestion(@RequestParam Long interviewId) {
        // 异步生成下一题，立即响应“处理中”
        CompletableFuture.runAsync(() -> {
            String question = interviewFlowService.generateNextQuestion(interviewId);
            String style = (String) redisTemplate.opsForValue().get("interview:style:" + interviewId);
            String audioBase64 = speechSynthesizerUtil.synthesizeToBase64(question, style);
            InterviewSession session = interviewSessionService.getById(interviewId);
            // ✅ 构建 JSON 字符串返回
            JSONObject json = new JSONObject();
            json.put("status", "done");
            json.put("questionText", question);
            json.put("audioBase64", audioBase64);
            json.put("roundIndex", TagUtil.intToTag(session.getRoundIndex()));

            String key = NEXT_QUESTION_RESULT_PREFIX + interviewId;
            stringRedisTemplate.opsForValue().set(key, json.toJSONString());
        });

        Map<String, Object> data = new HashMap<>();
        data.put("status", "processing");
        data.put("message", "处理中，请稍后轮询获取结果。");
        return ResultVO.success(data);
    }

    @GetMapping("/next-question/result")
    public ResultVO<Map<String, Object>> fetchNextQuestionResult(@RequestParam Long interviewId) {
        String key = NEXT_QUESTION_RESULT_PREFIX + interviewId;
        String resultJson = stringRedisTemplate.opsForValue().get(key);
        if (resultJson == null) {
            Map<String, Object> data = new HashMap<>();
            data.put("status", "processing");
            return ResultVO.success(data);
        } else {
            stringRedisTemplate.delete(key);
            Map<String, Object> data = JSON.parseObject(resultJson, Map.class);
            return ResultVO.success(data);
//            return ResultVO.success(result);  // 返回 JSON 字符串
        }
    }


    @Async("defaultExecutor")
    @PostMapping("/manual-question")
    public void uploadManualQuestionAsync(@RequestParam Long interviewId, @RequestParam String questionText) {
        String key = "interview:manual_question:" + interviewId;
        stringRedisTemplate.opsForValue().set(key, questionText);
    }



    // ⏹️ 面试结束后生成评估报告
    public static final String EVALUATION_REPORT_PREFIX = "interview:evaluation_report:";
    @PostMapping("/evaluation-report")
    public ResultVO<String> requestEvaluationReport(@RequestParam Long interviewId) {
        CompletableFuture.runAsync(() -> {
            String report = evaluationService.generateOverallEvaluationReport(interviewId);
            String key = EVALUATION_REPORT_PREFIX + interviewId;
            stringRedisTemplate.opsForValue().set(key, report);
        });

        return ResultVO.success("评估处理中，请稍后轮询获取结果...");
    }

    @GetMapping("/evaluation-report/result")
    public ResultVO<String> fetchEvaluationReportResult(@RequestParam Long interviewId) {
        String key = EVALUATION_REPORT_PREFIX + interviewId;
        String report = stringRedisTemplate.opsForValue().get(key);
        if (report == null) {
            return ResultVO.success("processing");
        } else {
            stringRedisTemplate.delete(key);
            return ResultVO.success(report);
        }
    }

}

